<template>
  <div class="dashboard-container">
    <h2>{{ type === "add" ? "新增房屋" : "修改房屋信息" }}</h2>
    <div class="dashboard-text">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称：" prop="title">
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="门牌号：" prop="propertyId">
          <el-input
            v-model="ruleForm.propertyId"
            placeholder="请输入门牌号"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="状态：" prop="state">
          <el-switch
            v-model="ruleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="整租价格（元）：" prop="price">
          <el-input
            v-model="ruleForm.price"
            placeholder="请输入整租价格（元）"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述：" prop="content">
          <el-input
            v-model="ruleForm.content"
            placeholder="请输入描述："
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input
            v-model="ruleForm.address"
            placeholder="请输入地址"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="封面：" prop="cover">
          <div>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :action="action"
              accept=".jpg, .jpeg, .JPG, .JPEG, .png, .PNG"
              :on-preview="handlePictureCardPreview"
              :on-remove="
                (file, fileList) => handleRemove(file, fileList, 'cover')
              "
              :on-success="
                (response, file, fileList) =>
                  handleSuccess(response, file, fileList, 'cover')
              "
            >
              <img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar">
              <i v-else class="el-icon-plus" />
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="轮播：" prop="carousel">
          <div>
            <el-upload
              :file-list="ruleForm.carousel"
              :action="action"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleListRemove"
              :on-success="handleListSuccess"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="房间样式图：" prop="styleImg">
          <div>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :action="action"
              accept=".jpg, .jpeg, .JPG, .JPEG, .png, .PNG"
              :on-preview="handlePictureCardPreview"
              :on-remove="
                (file, fileList) => handleRemove(file, fileList, 'styleImg')
              "
              :on-success="
                (response, file, fileList) =>
                  handleSuccess(response, file, fileList, 'styleImg')
              "
            >
              <img
                v-if="ruleForm.styleImg"
                :src="ruleForm.styleImg"
                class="avatar"
              >
              <i v-else class="el-icon-plus" />
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="房屋面积（平方米）：" prop="propertySize">
          <el-input
            v-model="ruleForm.propertySize"
            placeholder="请输入房屋面积"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="卧室数量：" prop="bedrooms">
          <el-input
            v-model="ruleForm.bedrooms"
            type="number"
            placeholder="请输入卧室数量"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="浴室数量：" prop="bathrooms">
          <el-input
            v-model="ruleForm.bathrooms"
            type="number"
            placeholder="请输入浴室数量"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="是否有车位：" prop="hasGarage">
          <el-switch
            v-model="ruleForm.hasGarage"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>

        <el-form-item label="建造年份：" prop="yearBuilt">
          <el-input
            v-model="ruleForm.yearBuilt"
            type="number"
            placeholder="请输入建造年份"
            maxlength="4"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="特色：" prop="features">
          <div class="checkbox-group">
            <el-checkbox-group v-model="ruleForm.features">
              <template v-for="(item, index) in featuresOptions">
                <el-checkbox :key="index" style="width: 80px" :label="item" />
              </template>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSaveContent">保存</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="type !== 'add'" class="disabled-table">
      <h2>查看订单</h2>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f5f5' }"
      >
        <el-table-column label="用户" prop="userInfo.username" />
        <el-table-column label="入住状态" prop="state">
          <template slot-scope="scope">
            {{ stateObj[scope.row.state] }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="更新时间" prop="updateTime" />
        <el-table-column label="操作" prop="op">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="onDetail(scope.row)"
            >删除</el-button>
            <el-button
              type="danger"
              @click="handleDel(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        :page-sizes="paginationConfig.pageSizes"
        :layout="paginationConfig.layout"
        :total="paginationConfig.total"
        :page="paginationConfig.page"
        :limit="paginationConfig.pageSize"
        @pagination="handleChangePage"
      />
    </div>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {
  createHousesDetail,
  getHousesDetail,
  updateHousesDetail
} from '@/api/house'
import { getOrderList } from '@/api/order'
export default {
  name: 'Dashboard',
  components: {},
  data() {
    return {
      action: process.env.VUE_APP_BASE_UPLOAD,
      dialogImageUrl: '',
      dialogVisible: false,
      ruleForm: {
        state: 1,
        price: '',
        address: '',
        content: '',
        avatar: '',
        title: '',
        cover: '',
        styleImg: '',
        features: [],
        carousel: [],
        propertySize: '',
        propertyId: '',
        bedrooms: '',
        bathrooms: '',
        hasGarage: 0,
        yearBuilt: ''
      },
      rules: {
        title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        content: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        price: [
          { required: true, message: '请输入整租价格（元）', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入整租价格（元）', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
        styleImg: [
          { required: true, message: '请上传房屋格局图样', trigger: 'blur' }
        ],
        propertySize: [
          { required: true, message: '请输入房屋面积', trigger: 'blur' }
        ],
        bedrooms: [
          { required: true, message: '请输入卧室数量', trigger: 'blur' }
        ],
        bathrooms: [
          { required: true, message: '请输入浴室数量', trigger: 'blur' }
        ],
        yearBuilt: [
          { required: true, message: '请输入建造年份', trigger: 'blur' }
        ],
        hasGarage: [
          { required: true, message: '请选择是否有车位', trigger: 'blur' }
        ],
        features: [
          { required: true, message: '请选择房屋特色', trigger: 'blur' }
        ],
        carousel: [
          { required: true, message: '请上传轮播图', trigger: 'blur' }
        ],
        propertyId: [
          { required: true, message: '请填写门牌号', trigger: 'blur' }
        ],
        state: [{ required: true, message: '请选择状态', trigger: 'blur' }]
      },
      tableData: [],
      stateObj: {
        0: '审核中',
        1: '入住中',
        2: '已退租'
      },
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      featuresOptions: [
        '空调',
        '冰箱',
        '床',
        '洗衣机',
        '电饭煲',
        '电饭锅',
        '24小时热水',
        '微波炉',
        '电吹风',
        '电风扇',
        '电烤箱',
        '电炖锅',
        '电饼铛',
        '电烧烤炉',
        '电火锅锅',
        '切菜刀',
        '可煮饭',
        '矿泉水',
        '24小时看护',
        '一对一看护',
        '全天候清洁'
      ]
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  created() {
    this.handleGetDetail()
    this.getList()
  },
  methods: {
    async handleGetDetail() {
      if (!this.$route.query.id) return
      const res = await getHousesDetail({
        id: this.$route.query.id
      })
      if (res.code === 200) {
        res.data.price = (res.data.price / 100).toFixed(2)
        this.ruleForm = Object.assign({}, res.data)
      }
    },
    async getList() {
      const res = await getOrderList({
        housesId: this.$route.query.id,
        page: this.paginationConfig.page,
        pageSize: this.paginationConfig.pageSize
      })
      if (res.code === 200) {
        this.tableData = res.data.list
        this.paginationConfig.total = res.data.total
      }
    },
    handleChangePage({ page, pageSize }) {
      this.paginationConfig.page = page
      this.paginationConfig.pageSize = pageSize
    },
    handleSaveContent() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(this.ruleForm))
          const api =
            this.type === 'add' ? createHousesDetail : updateHousesDetail
          const res = await api({
            ...form,
            price: form.price * 100,
            carousel: form.carousel.map((item) => {
              return {
                url: item.url
              }
            })
          })
          if (res.data && res.code === 200) {
            this.$message.success(
              `${this.type === 'add' ? '新建' : '保存'}成功`
            )
            this.$router.back()
          }
        }
      })
    },
    handleRemove(file, fileList, field) {
      console.log(file, fileList)
      // this.ruleForm.cover = ''
      this.$set(this.ruleForm, field, '')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(response, file, fileList, field) {
      if (response.code === 200) {
        file.url = response.data
        // this.ruleForm[field] = response.data
        this.$set(this.ruleForm, field, response.data)
      }
    },
    handleListSuccess(response, file, fileList) {
      if (response.code === 200) {
        file.url = response.data
        // this.ruleForm[field] = response.data
        this.$set(this.ruleForm, 'carousel', fileList)
      }
    },
    handleListRemove(file, fileList) {
      this.ruleForm.carousel = this.ruleForm.carousel.filter(
        (item) => item.uid !== file.uid
      )
    },
    handleDel() {},
    onDetail() {
      this.$router.push({
        name: 'orderDetail',
        query: {
          id: this.$route.query.id
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    margin-bottom: 30px;
  }
}
.el-input,
.el-textarea {
  width: 300px;
}
.box {
}
.box-card {
  display: inline-block;
  width: 32%;
  margin-right: 1%;
  .header {
    display: flex;
    align-items: flex-start;
  }
}
.checkbox-group {
  width: 380px;
}
.scope-box {
  .scope-item {
    margin-right: 1%;
    display: inline-block;
    width: 20%;
  }
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .el-upload--picture-card {
    display: inline-block !important;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
